#include "decision.h"
#include <QPainter>
#include <math.h>
#include "../flow/noteflow.h"
#include "pdlg_decision.h"

DecisionShape *DecisionShape::clone() const
{
	DecisionShape *newshape = new DecisionShape();
	newshape->setPos(this->pos());
	newshape->setSize(this->size());
	newshape->setConnectToCorners(this->connectToCorners());
	return newshape;
}

/**
 * Привязывает точку к узлам, если это задано.
 * @see Shape::flowConnectionPoint()
 */
QPointF DecisionShape::flowConnectionPoint (const QPointF &anotherEnd, Flow *flow) const
{
	if (!connectToCorners())
	{
		return Shape::flowConnectionPoint(anotherEnd, flow);
	}
	else
	{
		if (dynamic_cast<NoteFlow *>(flow))
			return Shape::flowConnectionPoint(anotherEnd, flow);

		QPointF pt = Shape::flowConnectionPoint(anotherEnd, flow);
		QPolygonF poly = QPolygonF()
			<< QPointF(size().width(), size().height()/2.0)
			<< QPointF(size().width()/2.0, size().height())
			<< QPointF(0, size().height()/2.0)
			<< QPointF(size().width()/2.0,0);
		bool firsttime = true;
		double len, minlen;
		int index=0;
		for(int i=0; i<poly.count(); ++i)
		{
			QPointF d = pt-poly.at(i);
			if ((len=sqrt(d.x()*d.x()+d.y()*d.y()))<minlen || firsttime)
				minlen=len, index=i, firsttime=false;
		}
		return poly.at(index);
	}
}

DecisionShape::DecisionShape (QGraphicsItem *parent)
	: ResizableShape(parent)
{
	setMinSize(QSizeF(30,20));
	setSize(QSizeF(50,30));

	 _connectToCorners = true;
	setConnectToCorners(_connectToCorners);
}

DecisionShape::DecisionShape (const QPointF &pos, QGraphicsItem *parent)
	: ResizableShape(pos, parent)
{
	setMinSize(QSizeF(30,20));
	setSize(QSizeF(50,30));

	_connectToCorners = true;
	setConnectToCorners(_connectToCorners);
}

void DecisionShape::paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	painter->setBrush(Shape::innerBrush());
	painter->setPen(Qt::black);
	painter->drawPath(shape());
	if (isSelected())
	{
		setPenAndBrushForSelection(painter);
		painter->drawRect(boundingRect());
	}
}

QPainterPath DecisionShape::shape() const
{
	QPainterPath path;
	path.addPolygon(
			QPolygonF()
				<< QPointF(size().width()/2.0,0)
				<< QPointF(size().width(), size().height()/2.0)
				<< QPointF(size().width()/2.0, size().height())
				<< QPointF(0, size().height()/2.0)
				<< QPointF(size().width()/2.0,0)
	);
	return path;
}

/**
 * @return true, если связи нужно привязывать к углам
 */
bool DecisionShape::connectToCorners() const
{
    return _connectToCorners;
}

/**
 * Задает, нужно ли привязывать точки присоединения к углам фигуры
 * @param newValue true, если нужно привязывать
 */
void DecisionShape::setConnectToCorners(bool newValue)
{
	prepareGeometryChange();
	_connectToCorners = newValue;
	emit Shape::placementChanged();
}

void DecisionShape::editProperties()
{
	DecisionShapePropertiesDialog(this).exec();
}
